﻿using Microsoft.Extensions.Logging;
using SKIT.FlurlHttpClient.Wechat.TenpayV3;
using SKIT.FlurlHttpClient.Wechat.TenpayV3.Models;
using SKIT.FlurlHttpClient.Wechat.TenpayV3.Settings;

namespace Vin.Extension.Framework.Wechat.Pay.Service;

public class CertificatesRefreshV3BaseService : VinWxPayV3BaseService
{
    const string AlgorithmType = "RSA";

    public async Task Refresh()
    {
        var request = new QueryCertificatesRequest() { AlgorithmType = AlgorithmType };
        if (WxPayClient == null)
        {
            Logger.LogWarning("未配置微信支付客户端，无法刷新微信商户平台证书。");
            return;
        }

        var response = await WxPayClient.ExecuteQueryCertificatesAsync(request);
        if (response.IsSuccessful())
        {
            // NOTICE: 如果构造 Client 时启用了 `AutoDecryptResponseSensitiveProperty` 配置项，则无需再执行下面一行的手动解密方法：
            response = WxPayClient.DecryptResponseSensitiveProperty(response);

            foreach (var certificate in response.CertificateList)
            {
                WxPayClient.PlatformCertificateManager.AddEntry(CertificateEntry.Parse(AlgorithmType, certificate));
            }

            Logger.LogInformation("刷新微信商户平台证书成功。");
        }
        else
        {
            Logger.LogWarning(
                "刷新微信商户平台证书失败（状态码：{0}，错误代码：{1}，错误描述：{2}）。",
                response.GetRawStatus(), response.ErrorCode, response.ErrorMessage
            );
        }
    }
}